package com.hurt.competition.player.controller;

import cn.hutool.extra.servlet.ServletUtil;
import com.hurt.competition.common.config.CommonConfig;
import com.hurt.competition.common.exception.CoreException;
import com.hurt.competition.common.util.CoreResultBuilder;
import com.hurt.competition.common.util.FileUtil;
import com.hurt.competition.common.vo.CoreResult;
import com.hurt.competition.player.dto.FileDownloadReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @PostMapping("/upload")
    public CoreResult upload(MultipartFile file) throws IOException {
        if(file == null){
            return CoreResultBuilder.error("file不能为空");
        }
        if(!FileUtil.validFileExt(file)){
            // 目前支持pdf和图片格式
            return CoreResultBuilder.error("file类型不支持");
        }

        String fileName = file.getOriginalFilename();
        String newFileLocation = CommonConfig.TEMPDIR + fileName;
        File newFile = new File(newFileLocation);
        file.transferTo(newFile);

        return CoreResultBuilder.success(newFile.getName());
    }

    @GetMapping("/preview")
    public void previewFile(String fileName, HttpServletResponse response) {
        try {
            File file = new File(CommonConfig.TEMPDIR + fileName);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            inputStream.read(bytes);
            response.setContentType(FileUtil.switchContentType(fileName));
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException("Failed to load file: " + e.getMessage());
        }
    }

    /**
     * 文件下载
     * @param req
     * @param response
     * @throws Exception
     */
    @PostMapping("download")
    public void downloadExampleFile(@RequestBody FileDownloadReq req, HttpServletResponse response) throws Exception {

        log.info("文件下载");
        String fileName = req.getFileName();
        String path = CommonConfig.TEMPDIR+fileName.trim();

//        ClassPathResource classPathResource = new ClassPathResource(path);
        File file = new File(path);
        if(!file.exists()){
            throw new CoreException("文件不存在");
        }
        InputStream inputStream = new FileInputStream(file);

        String name = path.substring(path.lastIndexOf("/")+1);
        response.setContentType("application/x-download");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
        //防止中文乱码
        response.setCharacterEncoding("UTF-8");
        ServletUtil.write(response,inputStream);
    }

}
